<template>
    <div class="page page-paths">
        <v-table
            ref="vTable"
            v-model="list"
            :height="compact ? '350' : 'auto'"
            :columns="columns"
            :func="getList"
            :showPagination="false"
            :compact="compact"
            :multiple="multipleEnabled"
            @selectionChange="handleSelectionChange"
            showCheckbox
            showIndex
        >
            <template #opts>
                <p-list-buttons
                    ref="btns"
                    :module="'paths'"
                    :buttons="buttons"
                    :compact="compact"
                    :ids="selectedPaths"
                    :list="list"
                    multiSelect
                    @clearIds="handleClearIds"
                    @editEnableChange="() => $emit('editEnableChange', true)"
                ></p-list-buttons>
            </template>
        </v-table>
    </div>
</template>

<script type="text/ecmascript-6">
import * as API from "../../../core/api.js";
import * as enums from '../../../store/status-enums.js';
import * as Chef from '../../../core/Chef.js';
import { mapState } from 'vuex';
import _ from 'lodash';
import bus from '../../../utils/Eventbus.js';
import vTable from '../../../utils/v-table/index.js';
import pListButtons from '../p-list-buttons.vue';
import Kernel from '../../../core/Kernel.js';
import i18n from '../../../lang/index.js';
const $t = i18n.global.t;

export default {
    name: 'paths',
    components: { vTable, pListButtons },
    props: {
        compact: Boolean // 紧凑模式
    },
    data () {
        return {
            list: [],
            columns: [
                { label: 'icon icon-lock', prop: 'lockExt', width: 30, isIcon: true, align: 'center' },
                { label: this.$t('lang.name'), prop: 'id', width: 60, align: 'right' },
                { label: this.$t('lang.color'), prop: 'colorExt', sortProp: 'color', width: 130, isBranchground: true },
                { label: this.$t('lang.label'), prop: 'labelExt', width: 120, isBranchground: true },
                { label: this.$t('lang.parts'), prop: 'partsExt', width: 60, align: 'right' },
                { label: this.$t('lang.length'), prop: 'lengthExt', sortProp: 'length', width: 70, align: 'right' },
                { label: this.$t('lang.absoluteSpeed'), prop: 'absoluteSpeedExt', width: 90, align: 'right' },
                { label: this.$t('lang.relativeSpeed'), prop: 'relativeSpeedExt', width: 90, align: 'right', isBranchground: true },
                { label: this.$t('lang.condition'), prop: 'conditionExt', width: 90, align: 'right', isBranchground: true },
                { label: this.$t('lang.turn'), prop: 'spotTurnExt', width: 60, isIcon: true, align: 'center' },
                { label: this.$t('lang.noEntry'), prop: 'closureExt', width: 60, isIcon: true, align: 'center' },
                { label: this.$t('lang.stopIt'), prop: 'stopSignExt', width: 60, isIcon: true, align: 'center' },
                // { label: this.$t('lang.initTime'), prop: 'initTimeExt', width: 130 },

                { label: this.$t('lang.initTime'), prop: 'initTimeExt', sortProp: 'initTime', width: 130 },
                { label: this.$t('lang.modified'), prop: 'modificationTimeExt', sortProp: 'modificationTime', width: 130 },
                // { label: this.$t('lang.modified'), prop: 'modificationTimeExt', width: 130 },
                { label: this.$t('lang.responsibility'), prop: 'responsibility', width: 110 },
                {
                    label: this.$t('lang.operate'),
                    fixed: 'right',
                    width: 180,
                    align: 'center',
                    opts: [
                        { label: this.$t('lang.detail'), type: 'info', icon: 'el-icon-document', callback: this.handleDetail },
                        { label: this.$t('lang.edit'), type: 'primary', icon: 'el-icon-edit', callback: this.handleModify },
                        { label: this.$t('lang.lock'), type: 'warning', icon: 'el-icon-lock', callback: this.handleLock },
                        { label: this.$t('lang.delete'), type: 'danger', icon: 'el-icon-delete', callback: this.handleDelete }
                    ]
                }
            ],
            buttons: ['edit', 'rebuild', 'merge', 'split', 'clonePaths', 'delete', 'lock', 'upload', 'download'],
            disableOpts: false,
            multipleSelection: []
        };
    },
    computed: {
        ...mapState({
            openedBoxes: state => state.businessStatus.openedBoxes,
            isAltFnActive: state => state.businessStatus.isAltFnActive,
            isDrawPathsActive: state => state.businessStatus.isDrawPathsActive,
            selectedPaths: state => state.businessStatus.selectedPaths
        }),
        multipleEnabled() {
            return this.compact ? this.isAltFnActive : true;
        }
    },
    watch: {
        compact: { handler () { this.init(); }, deep: true },
        // '$root.ws.serverTime'() { this.initAsync(); }
        // selectedPaths(val) {
        //     // if (this.compact && val && val.length) this.toggleRowSelection(val);
        //     if (this.compact) this.toggleRowSelection(val);
        // }
    },
    created() {
        bus.on(`paths.toggleRowSelection`, this.toggleRowSelection);
    },
    mounted() {
        this.init();
    },
    beforeDestroy() {
        console.log('paths.beforeDestroy: ');
        this.$store.commit(enums.DESELECT_PATHS_ALL);
        bus.off(`paths.toggleRowSelection`, this.toggleRowSelection);
        if (this.kernel) this.kernel.off('handleIncrement', this.handleIncrementFunc);
    },
    methods: {
        init() {
            let idx = this.columns.findIndex(v => v.opts);
            if (this.compact && idx >= 0) this.columns[idx].hidden = true;
            else if (idx >= 0) this.columns[idx].true = false;
            this.kernel = Kernel.getInstance();
            this.kernel.on('handleIncrement', this.handleIncrementFunc);
        },
        handleIncrementFunc(res) {
            if (!res || !res.refreshTypes || !res.refreshTypes[this.$options.name]) return;
            this.initAsync();
        },
        // initAsync() {
        //     this.list.forEach(v => Chef.extendPathAsync(v, this.$root.resources.paths));
        // },
        initAsync: _.throttle(function() {
            if (this.compact && this.openedBoxes.indexOf(`${this.$options.name}Table`) < 0) return;
            if (!this.$root.resources.paths || this.list.length !== this.$root.resources.paths.length) {
                if (!this.$root.resources.paths && this.list.length === 0) return;
                if (this.$refs.vTable && this.$refs.vTable.truename) bus.emit(`${this.$refs.vTable.truename}.init`);
                return;
            }
            this.list.forEach(v => Chef.extendPathAsync(v, this.$root.resources.paths));
        }, 1000),
        getList() {
            return API.getLocalResources('paths').then(res => {
                let rtn = {...res};
                // res.list = res.list.slice(0, 20);
                if (res && res.list && res.list.length) rtn.list = Chef.extendPaths(res.list);
                return rtn;
            });
        },
        // Trigger from table
        handleSelectionChange(ids) {
            if (ids.indexOf('-1') !== -1) return;
            if (ids.length === this.selectedPaths.length && ids.every(v => this.selectedPaths.indexOf(v) !== -1)) return;
            console.log('paths.handleSelectionChange: ', ids);
            this.$store.commit(enums.DESELECT_PATHS_ALL, ids);
            this.$emit('selectionChange', ids);
        },
        // Trigger from vuex
        toggleRowSelection(ids) {
            if (ids.indexOf('-1') !== -1) return;
            // if (ids.length === this.selectedPaths.length && ids.every(v => this.selectedPaths.indexOf(v) !== -1)) return;
            console.log('paths.toggleRowSelection: ', ids);
            this.$refs.vTable.toggleRowSelection(ids);
        },
        handleClearIds(ids) {
            console.log('paths.handleClearIds: ');
            this.$store.commit(enums.DESELECT_PATHS_ALL, ids);
            // this.$refs.vTable.toggleRowSelection(ids);
        },
        // opts callback
        handleDetail(e, row) {
            // this.$router.push({ name: 'path-detail', params: { type: 'read', ids: [row.id] } });
            this.$router.push({ name: 'path-detail', params: { type: 'read', id: row.id } });
        },
        handleModify(e, row) {
            // this.$router.push({ name: 'path-detail', params: { type: 'mod', ids: [row.id] } });
            this.$router.push({ name: 'path-detail', params: { type: 'mod', id: row.id } });
        },
        handleLock(e, row) {
            this.$refs.btns.handleLock(e, [row.id]);
        },
        handleDelete(e, row) {
            this.$refs.btns.handleDelete(e, [row.id]);
        }
    }
};
</script>

<style lang="scss">
.page-paths {
}
</style>
